package com.quzhi.sys.controller.UserController;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quzhi.common.Result;
import com.quzhi.common.code.Code;
import com.quzhi.sys.dto.UserDto;
import com.quzhi.sys.entity.Role;
import com.quzhi.sys.entity.User;
import com.quzhi.sys.entity.UserRole;
import com.quzhi.sys.service.IUserService;
import com.quzhi.sys.service.impl.RoleServiceImpl;
import com.quzhi.sys.service.impl.UserRoleServiceImpl;
import com.quzhi.sys.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Slf4j
@RestController
@RequestMapping("/sys/user")
public class UserController {


    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private UserRoleServiceImpl userRoleService;

    @Autowired
    private RoleServiceImpl roleService;


    @Autowired
    private PasswordEncoder passwordEncoder;


    // 登录
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        // 查询数据库，没有数据则登录失败
        return userService.login(user);
    }


    @GetMapping("/info")
    public Result<Map<String, Object>> info(@RequestParam("token") String token) {

        Map<String, Object> data = userService.getUserinfo(token);

        if (data != null) {
            return Result.success(data);

        }

        return Result.fail(20002, "用户信息有误，请重新登录");

    }

    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("qz-Token") String qz_token) {
        userService.logout(qz_token);

        return Result.success();
    }

    // 获取用户
    @GetMapping("/list")
    public Result<Map<String, Object>> getUserList(@RequestParam(value = "username", required = false) String username,
                                                   @RequestParam(value = "phone", required = false) String phone,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();


        // 通过用户名或手机号码模糊查询
        wrapper.like(StringUtils.hasLength(username), User::getUsername, username)
                .like(StringUtils.hasLength(phone), User::getPhone, phone).orderByDesc(User::getId);
        Page<User> page = new Page<>(pageNo, pageSize);
        userService.page(page, wrapper);
        Map<String, Object> data = new HashMap<>();

        // 删除管理员，并把密码清空
        List<User> records = page.getRecords();


        List<Map<String, Object>> rows = new ArrayList<>();

        for (User record : records) {
            UserDto user = new UserDto();
            BeanUtils.copyProperties(record, user);


            // 用户所有权限
            LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userRoleLambdaQueryWrapper.eq(UserRole::getUserId, user.getId());
            List<UserRole> userRoles = userRoleService.list(userRoleLambdaQueryWrapper);
            List<String> roles = new ArrayList<>();

            for (UserRole userRole : userRoles) {
                // 查询选项名称
                LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                roleLambdaQueryWrapper.eq(Role::getRoleId, userRole.getRoleId());
                Role roleServiceOne = roleService.getOne(roleLambdaQueryWrapper);
                roles.add(roleServiceOne.getRoleDesc());
            }

            user.setRoles(roles);

            boolean flag = true;
            for (String role : user.getRoles()) {
                if (role.equals("超级管理员")) {
                    flag = false;
                    break;
                }
            }

            if (flag) {
                Map<String, Object> row = new HashMap<>();
                row.put("id", user.getId());
                row.put("username", user.getUsername());
                row.put("avatar", user.getAvatar());
                row.put("phone", user.getPhone());
                row.put("status", user.getStatus());
                row.put("roles", user.getRoles());

                rows.add(row);
            }

        }


        data.put("total", page.getTotal() - 1);
        data.put("rows", rows);

        return Result.success(data);

    }

    @PostMapping
    public Result<?> addUser(@RequestBody UserDto user) {


        return userService.addUser(user);
    }


    @PutMapping
    public Result<?> updateUser(@RequestBody UserDto user) {
        User updateUser = userService.getById(user.getId());

        UserDto userDto = new UserDto();
        updateUser.setAvatar(user.getAvatar());
        updateUser.setUsername(user.getUsername());
        updateUser.setStatus(user.getStatus());
        updateUser.setPhone(user.getPhone());
        BeanUtils.copyProperties(updateUser, userDto);

        userDto.setRoles(user.getRoles());


        return userService.updateUser(userDto);
    }


    /**
     * 用户修改信息
     */
    @PutMapping("/updateUserInfo")
    public Result<?> updateUser(@RequestBody User user) {
        // 查询用户名是是否存在存在则不更新
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User one = userService.getOne(wrapper);
        if (one != null) {
            if(user.getId() != null && !one.getId().equals(user.getId())){
                return Result.fail(Code.UPDATE_FAIL_CODE, "用户名已存在");
            }
        };

        User updateUser = userService.getById(user.getId());

        updateUser.setAvatar(user.getAvatar());
        updateUser.setUsername(user.getUsername());
        updateUser.setPhone(user.getPhone());

        userService.updateById(updateUser);

        return Result.success("更新成功");
    }


    @GetMapping("/{id}")
    public Result<?> getUserById(@PathVariable("id") String id) {
        User user = userService.getById(id);

        // 获取用户权限
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, id);
        List<UserRole> list = userRoleService.list(wrapper);

        // 所有权限集合
        List<String> roles = new ArrayList<>();
        for (UserRole userRole : list) {
            Role byId = roleService.getById(userRole.getRoleId());
            roles.add(byId.getRoleDesc());
        }

        Map<String, Object> reUser = new HashMap<>();
        reUser.put("id", user.getId());
        reUser.put("username", user.getUsername());
        reUser.put("status", user.getStatus());
        reUser.put("avatar", user.getAvatar());
        reUser.put("phone", user.getPhone());
        reUser.put("roles", roles);

        return Result.success(reUser);
    }

    /**
     * 通过用户名称获取用户
     *
     * @return 不返回权限，只返回 用户ID，用户名，手机号，头像
     */
    @GetMapping("/getByName")
    public Result<?> getUserByName(@RequestParam String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);

        User user = userService.getOne(lambdaQueryWrapper);

        Map<String, String> data = new HashMap<>();

        data.put("id", user.getId());
        data.put("username", user.getUsername());
        data.put("phone", user.getPhone());
        data.put("avatar", user.getAvatar());

        return Result.success(data);
    }


    @DeleteMapping("/{id}")
    public Result<User> deleteUserById(@PathVariable("id") String id) {

        // 删除用户所有权限
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUserId, id);
        userRoleService.remove(userRoleLambdaQueryWrapper);


        userService.removeById(id);

        return Result.success("删除用户成功");
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword/{id}")
    public Result<?> updatePassWord(@PathVariable String id, @RequestBody Map<String, Object> password) {
        String rePassword = (String) password.get("rePassword"); // 原密码
        String upPassword = (String) password.get("upPassword"); // 修改密码
        boolean model = (boolean) password.get("model"); // 模式0为需要原密码相同，1,为强行修改
        // 查询用户
        User user = userService.getById(id);

        if (model) {
            // 强行修改
            // 原密码相同可以修改
            user.setPassword(passwordEncoder.encode(upPassword));

            userService.updateById(user);

        } else {
            if (passwordEncoder.matches(rePassword, user.getPassword())) {
                // 原密码相同可以修改
                user.setPassword(passwordEncoder.encode(upPassword));

                userService.updateById(user);
            } else {
                return Result.fail(Code.UPDATE_FAIL_CODE, "原密码错误，修改失败");
            }
        }

        return Result.success("修改成功");
    }

}
